#!/usr/bin/lua
--https://www.lua.org/pil/16.html

Submarine = {
    position = 0,
    depth = 0,
    direction_lookup = {
        ['forward'] = {0, 1, 1},
        ['up'] = {1, 0, -1},
        ['down'] = {1, 0, 1}
    }
}

function Submarine:new (o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    print('position', self.position, self.depth)
    return o
end

function Submarine:move (direction, units)
    a = self.direction_lookup[direction]
    self.position = self.position + a[2] * a[3] * units
    self.depth = self.depth + a[1] * a[3] * units
    print('new position', self.position, self.depth)
end

function Submarine:encode_position ()
    return self.position * self.depth
end

sub = Submarine:new()

while true do
    local line = io.read()
    if line == nil then break end
    _, _, direction, units = string.find(line, "(%a+)%s(%d+)")
    print(direction, units)
    if not pcall(sub.move, sub, direction, tonumber(units)) then
        print('invalid command')
    end
end

print('distance', sub:encode_position())
